package com.compass.mobile.ui.fragment

import LogUtil
import UserInfoManager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.recyclerview.widget.RecyclerView
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentRegistrationPoolBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.APPOINTMENT_ACTION
import com.compass.mobile.framework.constant.KEY_DOCTOR_ID
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.HisNumberTank
import com.compass.mobile.models.ReservationDate
import com.compass.mobile.models.TicketModel
import com.compass.mobile.presenters.HisNumberTankPresenter
import com.compass.mobile.presenters.RegistrationPoolPresenter
import com.compass.mobile.ui.activity.IndependentBillingActivity
import com.compass.mobile.ui.dialog.AgreementDialog
import com.compass.mobile.ui.dialog.CustomerServiceCode
import com.compass.mobile.ui.dialog.NumberSegmentDialog
import com.compass.mobile.ui.viewModel.DoctorViewModel
import com.compass.mobile.ui.viewModel.MainViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource
import toJson

/**
 * Description： 挂号池
 * Date:2024/5/23 21:35
 */
class RegistrationPoolFragment : BaseVBFragment<FragmentRegistrationPoolBinding>() {
    private var doctorId: String? = null
    private var type: String? = null     //time_point  表示根据时间点查询      time_slot  表示根据时间段查询
    private lateinit var numberSegmentDialog: NumberSegmentDialog.Builder
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private val doctorViewModel: DoctorViewModel by activityViewModels()

    private val mainViewModel: MainViewModel by viewModels()

    private var reservationDate: MutableList<ReservationDate> = mutableListOf()
    private var hisNumberTankList: MutableList<HisNumberTank> = mutableListOf()
    private var tickets: MutableList<TicketModel> = mutableListOf()
    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            doctorId = it.getString(KEY_DOCTOR_ID)
        }
        specialColumn()
        FocusViewUtils.scaleView(mBinding?.llFollow, 0)
        FocusViewUtils.scaleView(mBinding?.llConsultationRecord, 0)

    }

    override fun initData() {
        doctorViewModel.doctorHomePageLiveData.observe(this) {
            it?.let { doctorWarp ->
                val list = doctorWarp.hisDocResSchInfoParentVOList

                if (!list.isNullOrEmpty()) {
                    initHisTitle(list)
                } else {
                    mBinding?.emptyView?.visible()
                    mBinding?.outpatientDepartment?.gone()
                    mBinding?.registrationPool?.gone()

                }
                setFollow(doctorWarp.doctor.follow)

            }
        }
        doctorViewModel.followLiveData.observe(this) {
            it?.let {
                setFollow(it)
            }
            dismissLoading()
        }
        doctorViewModel.ticketsLiveData.observe(this) {

            it?.let { ticketModel ->
                type = ticketModel.type
                if (isAm) {
                    tickets.addAll(ticketModel.list)
                    reservation?.pm?.let { numberSource ->
                        isAm = false
                        doctorViewModel.getTickets(numberSource.pkSch)
                    } ?: kotlin.run {
                        show()

                    }
                } else {
                    tickets.addAll(ticketModel.list)
                    show()

                }

            }?:kotlin.run {
                dismissLoading()
            }
        }
        doctorViewModel.saveAppointmentLiveData.observe(this) {
            dismissLoading()
            it?.let {

                CustomerServiceCode.Builder(requireActivity(), APPOINTMENT_ACTION).show()

            }

        }

        mainViewModel.agreementLiveData.observe(this){ htmlDate->
            AgreementDialog.Builder(requireActivity(),5, htmlDate)
                .setConfirm(getStringFromResource(R.string.ui_dialog_switch_call_type_positive))
                .setCancel(getStringFromResource(R.string.ui_dialog_switch_call_type_negative))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    it?.dismiss()
                    getTicketsData()
                }.create().show()

        }
    }

    private fun setFollow(follow: String) {
        mBinding?.tvFollow?.text = if (follow == "1") "已关注" else "关注医生"
    }

    override fun intListener() {
        mBinding?.llFollow?.onClick {
            showLoading()
            doctorViewModel.follow(doctorId, UserInfoManager.getPatientInfo()?.id)
        }


    }


    private val onTicketItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            if (::numberSegmentDialog.isInitialized) {
                numberSegmentDialog.dismissDialog()
            }

            LogUtil.d("info===${tickets[position].toJson()}")
            showLoading()
            //time_point  表示根据时间点查询      time_slot  表示根据时间段查询
            //时间点传ticketNo字段内容           时间段传dateslot字段内容
            var param:String=""
            when(type){
                "time_point"->{
                    param=tickets[position].ticketno
                }
                "time_slot"->{
                    param=tickets[position].dateSlot
                }
            }

            doctorViewModel.saveAppointment( UserInfoManager.getPatientInfo()?.id,  tickets[position].pkSch,  param )
        }
    }

    private fun show() {
        dismissLoading()
        numberSegmentDialog =
            NumberSegmentDialog.Builder(requireActivity(), tickets, onTicketItemClickListener)
        numberSegmentDialog.show()
    }

    private var reservation: ReservationDate? = null
    private var isAm: Boolean = true//加载早上排班
    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            reservation = reservationDate[position]
            tickets.clear()
            checkTickets()


        }
    }

    /**
     * 检测是否有排班
     */
    private fun checkTickets(){
        reservation?.am?.let {
            isAm = true
            showLoading()
            mainViewModel.getHospitalConfig("reservation.content.notice")
        } ?: kotlin.run {
            reservation?.pm?.let {
                isAm = false
                showLoading()
                mainViewModel.getHospitalConfig("reservation.content.notice")
            } ?: kotlin.run {

                showToast("该日期暂无排班")
            }
        }
    }


    private fun getTicketsData(){
        reservation?.am?.let {
            isAm = true
            showLoading()
            doctorViewModel.getTickets(it.pkSch)
        } ?: kotlin.run {

            reservation?.pm?.let {
                isAm = false
                showLoading()
                doctorViewModel.getTickets(it.pkSch)
            } ?: kotlin.run {

                showToast("该日期暂无排班")
            }
        }
    }


    private val onChildViewHolderSelectedListener: OnChildViewHolderSelectedListener = object :
        OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView?,
            child: RecyclerView.ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            hisNumberTankList[0].reservationDateVOList?.let {
                reservationDate = it
                arrayObjectAdapter.clear()
                arrayObjectAdapter.addAll(0, reservationDate)
            }


        }
    }

    @SuppressLint("RestrictedApi")
    fun initHisTitle(hisNumbers: MutableList<HisNumberTank>) {
        hisNumberTankList = hisNumbers
        mBinding?.outpatientDepartment?.setHorizontalSpacing(dpToPx(20))
        val arrayObjectAdapter = ArrayObjectAdapter(HisNumberTankPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(requireContext(), arrayObjectAdapter, null)
        mBinding?.outpatientDepartment?.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, hisNumberTankList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
        mBinding?.outpatientDepartment?.setOnChildViewHolderSelectedListener(
            onChildViewHolderSelectedListener
        )
        mBinding?.outpatientDepartment?.requestFocus()
    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {
        mBinding?.registrationPool?.setNumColumns(7)
        mBinding?.registrationPool?.horizontalSpacing = dpToPx(10)
        mBinding?.registrationPool?.verticalSpacing = dpToPx(10)

        arrayObjectAdapter = ArrayObjectAdapter(RegistrationPoolPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )
        mBinding?.registrationPool?.setAdapter(itemBridgeAdapter)
        mBinding?.registrationPool?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, reservationDate)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_SMALL, false
        )

    }


}